package cn.tedu.order.service;

import cn.tedu.order.entity.Order;
import cn.tedu.order.feign.EasyIdClient;
import cn.tedu.order.mapper.OrderMapper;
import cn.tedu.order.mapper.TXMapper;
import cn.tedu.order.entity.AccountMessage;
import cn.tedu.order.entity.TxInfo;
import cn.tedu.order.util.JsonUtil;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;
@RocketMQTransactionListener
@Service
 //RocketMQTransaction事务监听器--->本地事务状态【重写两个方法】
public class OrderServiceImpl implements OrderService, RocketMQLocalTransactionListener {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private EasyIdClient easyIdClient;
   @Autowired
   private RocketMQTemplate t;//模板

   @Autowired
   private TXMapper txMapper;//
    /**
     * 不再使用feign技术同步调用远程的库存和账户模块业务
     * 采用rockmq异步调用
     *
     */
    @Override
    public void create(Order order){
        //用uuid产生事务id
        String xid = UUID.randomUUID().toString().replace("-", "");
        AccountMessage am = new AccountMessage(order.getUserId(),order.getMoney(),xid);
        String json = JsonUtil.to(am);//通过该工具自动转换json串
        Message<String> message = MessageBuilder.withPayload(json).build();//Payload自动转换byte数组

        //发送消息
        t.sendMessageInTransaction("orderTopic",message,order);
    }

//    @Autowired
//    private StorageClient storageClient;
//    @Autowired
//    private AccountClient accountClient;
//    @GlobalTransactional  //启动全局事务

    public void doCreate(Order order) {
        //  远程调用发号器，获取订单id
        String s = easyIdClient.nextId("order_business");
        Long orderId = Long.valueOf(s);

        order.setId(orderId);
        orderMapper.create(order);

        // 远程调用库存，减少库存
     //   storageClient.decrease(order.getProductId(),order.getCount());
        // 远程调用账户，扣减账户
     //  accountClient.decrease(order.getUserId(),order.getMoney());
    }
   @Transactional //执行事务/处理事务
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        RocketMQLocalTransactionState state;//返回数据
        int status;//存储数据库


       try {
           Order order = (Order) o;
           doCreate(order);
          state= RocketMQLocalTransactionState.COMMIT;
           status = 0;
       } catch (Exception e) {
         state=  RocketMQLocalTransactionState.ROLLBACK;
         status=1;
           e.printStackTrace();
       }
       String json = new String((byte[]) message.getPayload());
       String xid = JsonUtil.getString(json, "xid");
       //封装整个事务状态
       TxInfo txInfo = new TxInfo(xid, status, System.currentTimeMillis());
            txMapper.insert(txInfo);//实体事务对象
       return state;
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        String json = new String((byte[]) message.getPayload());
        String xid = JsonUtil.getString(json, "xid");
        TxInfo txInfo = txMapper.selectById(xid);
        if(txInfo==null){
            return RocketMQLocalTransactionState.UNKNOWN;
        }
        switch (txInfo.getStatus()){
            case 0 : return RocketMQLocalTransactionState.COMMIT;
            case 1 : return RocketMQLocalTransactionState.ROLLBACK;
            default:return RocketMQLocalTransactionState.UNKNOWN;
        }


    }
}
